#ifndef _REACTOR_EVENT_H
#define _REACTOR_EVENT_H

#define EVBUF_SIZE 2048

#define EV_READ_INT 0
#define EV_WRITE_INT 1
#define EV_SIGNAL_INT 2
#define EV_CONNECT_INT 3
#define EV_ACCEPT_INT 4
#define EV_RING_INT 28
#define EV_BREAK_INT 28
#define EV_ERR_INT 29
#define EV_FORCE_OFF_INT 30
#define EV_SLEEP_INT 31

#define EV_READ (1 << EV_READ_INT)
#define EV_WRITE (1 << EV_WRITE_INT)
#define EV_SIGNAL (1 << EV_SIGNAL_INT)
#define EV_CONNECT (1 << EV_CONNECT_INT)
#define EV_ACCEPT (1 << EV_ACCEPT_INT)
#define EV_RING (1 << EV_RING_INT)
#define EV_BREAK (1 << EV_BREAK_INT)
#define EV_ERR (1 << EV_ERR_INT)
#define EV_FORCE_OFF (1 << EV_FORCE_OFF_INT)
#define EV_SLEEP (1 << EV_SLEEP_INT)

#define EVBUF_NR_OBJ 2

#define EVMODE_NORMAL_INT 0
#define EVMODE_ONCE_INT 1
#define EVMODE_ASYNC_INT 2
#define EVMODE_IOPOOL_INT 3
#define EVMODE_ET_INT 4

#define EVMODE_NORMAL (1 << EVMODE_NORMAL_INT)
#define EVMODE_ONCE (1 << EVMODE_ONCE_INT)
#define EVMODE_ASYNC (1 << EVMODE_ASYNC_INT)
#define EVMODE_IOPOOL (1 << EVMODE_IOPOOL_INT)
#define EVMODE_ET (1 << EVMODE_ET_INT)

struct event;
struct event_base;
struct event_worker;

typedef void event_cb_t(struct event *, u_int, struct evbuf *, void *);

typedef struct evbuffer_object {
    int active;
    int len;
    u8 buf[EVBUF_SIZE];
    u8 *buf_ptr;
    
    struct list_head node;
} evbuffer_object_t;

struct evtimer {
	event_cb_t *cb;
	uint64_t deadline;
	struct list_head list;
	struct rb_node node;
};

typedef struct evbuf_off {
    int remain;
    u8 *bufoff;
} evbuf_off_t;

struct evbuf {
    int len;
    u8 *buf;
    event_cb_t *cb;
    
    struct evbuf_off rsv;
    struct list_head node;
};

struct evbuf_hand {
    event_cb_t *cb;
    struct sockaddr_in sa;

	struct evbuf_off rsv;
    struct list_head node;
};

struct evbuffer {
    struct list_head idle;
    struct list_head qr;
    struct list_head qw;
    struct list_head qc;
    struct list_head qa;
    
    int nr;
    struct evbuffer_object *inuse;
};

struct event {
    struct list_head signal_node;
    struct list_head active_node;
    struct list_head sleep_node;

    int sockfd;
    struct event_base *base;
    int mode;
    int mode_setting;
    int et_mode;

    int watch;
    int insert;
    int signal;

    struct evbuffer *buf;
    struct evtimer timer;
    int on_timer;
    
    void *arg;
    event_cb_t *cb;
    
    event_cb_t *dcb;
};

struct event_worker {
    int id;
    int lock;
	int status;
    
    struct list_head signal_queue;
	struct event_base *base;
};

struct event_base {
    struct list_head signal_queue;
    struct list_head active_queue;
    struct list_head sleep_queue;
    
	int nr_cpu;
	int nr_active_worker;
	struct event_worker **worker_vec;
	struct rb_root timer_tree;
	int nr_timer;
	
    struct event_syscall *sysop;
    
    void *(*malloc)(unsigned int);
    void (*free)(void *);
    void *(*realloc)(void *, unsigned int);
};

#endif